/*
This file is part of SmartShopper

SmartShopper is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

SmartShopper is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with vlc-remote.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <QString>
#include <QSqlQuery>
#include <QSqlRecord>
#include <QSqlField>
#include <QDebug>
#include "shoplistmodel.h"
#include "shoplistobject.h"

// ShopList model with accessible from QML properies
// has setters for filter of objects
// can connect to DB, select, update

ShopListModel::ShopListModel(QObject *parent) :
    QAbstractListModel(parent)
{
    QHash<int, QByteArray> roles;
    roles[IdRole] = "id";
    roles[NameRole] = "listName";
    roles[ShopRole] = "shopName";
    roles[StoreIdRole] = "shopId";
    roles[StateIdRole] = "stateId";
    setRoleNames(roles);
}

ShopListModel::~ShopListModel()
{
    clear();
}

void ShopListModel::addShopList(const ShopListObject &list)
{
    beginInsertRows(QModelIndex(), rowCount(), rowCount());
    m_lists << list;
    endInsertRows();
}

void ShopListModel::removeShopList(const int indx)
{
    if(indx < 0 || indx >= m_lists.size()) return;
    beginRemoveRows(QModelIndex(), indx, indx);
    m_lists.removeAt(indx);
    endRemoveRows();
}

ShopListObject& ShopListModel::getShopList(int indx)
{
    return m_lists[indx];
}

int ShopListModel::rowCount(const QModelIndex & parent) const {
    return m_lists.count();
}

QVariant ShopListModel::data(const QModelIndex & index, int role) const {
    if (index.row() < 0 || index.row() > m_lists.count())
        return QVariant();

    const ShopListObject &list = m_lists[index.row()];
    if (role == IdRole)
        return list.id();
    else if (role == NameRole)
        return list.name();
    else if (role == ShopRole)
        return list.storeName();
    else if (role == StoreIdRole)
        return list.storeId();
    else if (role == StateIdRole)
        return list.stateId();
    return QVariant();
}

void ShopListModel::clear()
{
 // qDeleteAll(m_lists);
    int num = m_lists.count();
    for (int i = 0; i < num; i++)
    {
        beginRemoveRows(QModelIndex(), 0, 0);
//    if (!m_lists.isEmpty())
        m_lists.removeAt(0);
        endRemoveRows();
    }

  //m_lists.clear();
}
